package com.qiangesoft.datasource.core;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.util.HashMap;
import java.util.Map;

/**
 * 多数据源配置
 *
 * @author qiangesoft
 * @date 2024-03-14
 */
@Slf4j
@Configuration
public class DataSourceConfiguration {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.master")
    public DruidDataSource masterDataSource() {
        DruidDataSource masterDataSource = DruidDataSourceBuilder.create().build();
        masterDataSource.setName(DataSourceType.MASTER.getType());
        return masterDataSource;
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.slave")
    @ConditionalOnProperty(prefix = "spring.datasource.druid.slave", name = "enabled", havingValue = "true")
    public DruidDataSource slaveDataSource() {
        DruidDataSource slaveDataSource = DruidDataSourceBuilder.create().build();
        slaveDataSource.setName(DataSourceType.SLAVE.getType());
        return slaveDataSource;
    }

    @Bean
    @Primary
    public DynamicDataSource dynamicDataSource(DruidDataSource masterDataSource, DruidDataSource slaveDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(masterDataSource.getName(), masterDataSource);
        targetDataSources.put(slaveDataSource.getName(), slaveDataSource);
        return new DynamicDataSource(masterDataSource, targetDataSources);
    }
}
